<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <el-button type="success" size="default" @click="addRole"
          >新增角色</el-button
        >
      </div>
      <el-table :data="tableList" border style="width: 100%">
        <el-table-column type="index" label="#" align="center">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center">
        </el-table-column>
        <el-table-column prop="roleCode" label="角色编码" align="center">
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="活动时间" align="center">
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="default"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="default" @click="delRole(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="start"
          :page-sizes="[8, 16]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="fullData"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="提示"
      @close="resetForm"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form
        :model="formList"
        ref="form"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="角色名称">
          <el-input v-model="formList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="formList.roleCode"></el-input>
        </el-form-item>
        <el-form-item label="活动形式">
          <el-input type="textarea" v-model="formList.remark"></el-input>
        </el-form-item>
        <el-form-item label="选择菜单">
          <!-- <el-input type="textarea" v-model="form.remark"></el-input> -->
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-checkbox
                v-model="show"
                @change="closeToggle"
                :indeterminate="false"
                >展开/关闭</el-checkbox
              >
              <el-checkbox
                v-model="checkedAll"
                @change="checkedAllToggle"
                :indeterminate="false"
                >全选/取消权限</el-checkbox
              >
            </el-col>
            <el-col :span="12" :offset="0">
              <el-tree
                :data="treeData"
                ref="tree"
                show-checkbox
                :default-expand-all="false"
                node-key="id"
                @check="change"
                highlight-current
                :props="defaultProps"
              >
              </el-tree>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitCreatedRole">确 定</el-button>
      </span>
    </el-dialog>
    <buttomBanner></buttomBanner>
  </div>
</template>

<script>
import {
  findRolesByPage,
  removeRole,
  saveRolePermissions,
  findAllPermissions,
  updateRolePermissions,
} from "@/api/permissions/role/role.js";
import buttomBanner from "@/components/buttomBanner";
export default {
  name: "Role",
  data() {
    return {
      num: 0,
      nodeCheckId: [],
      dialogVisible: false,
      show: false,
      checkedAll: false,
      formList: {},
      treeData: [],
      defaultProps: {
        label: "title",
        children: "children",
      },
      tableList: [],
      start: 1,
      limit: 8,
      fullData: 0,
    };
  },
  components:{
    buttomBanner
  },
  methods: {
    // 取消弹窗清空表单
    resetForm() {
      this.formList = {};
    },
    // 提交创建角色
    commitCreatedRole() {
      var role = {
        ...this.formList,
        permissionIds: this.nodeCheckId,
      };
      var api;
      // 判断是新增角色还是编辑角色
      if (this.num) {
        api = updateRolePermissions;
      } else {
        api = saveRolePermissions;
      }
      api(role).then((res) => {
        if (res.success) {
          this.$message.success("提交成功");
          this.$refs.tree.setCheckedKeys([]);
          this.show = false;
          this.checkedAll = false;
          for (
            var i = 0;
            i < this.$refs.tree.store._getAllNodes().length;
            i++
          ) {
            this.$refs.tree.store._getAllNodes()[i].expanded = false;
          }
        } else {
          this.$message.error(res.message);
        }
        this.init();
        this.dialogVisible = false;
      });
    },
    // 改变单个树形组件多选框
    change() {
      var item = this.$refs.tree.getCheckedNodes();
      item.forEach((el) => {
        this.nodeCheckId.push(el.id);
      });
    },
    // 切换树形数据关闭展开
    closeToggle() {
      for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
        this.$refs.tree.store._getAllNodes()[i].expanded = this.show;
      }
    },
    // 切换树形数据全选全不选
    checkedAllToggle() {
      var item = [];
      if (this.checkedAll) {
        this.$refs.tree.setCheckedNodes(this.treeData);
        item = this.$refs.tree.getCheckedNodes();
        item.forEach((el) => {
          this.nodeCheckId.push(el.id);
        });
      } else {
        this.$refs.tree.setCheckedKeys([]);
        item = this.$refs.tree.getCheckedNodes();
        this.nodeCheckId = [];
      }
    },
    // 新增角色
    addRole() {
      this.num = 0;
      this.dialogVisible = true;
    },
    // 编辑角色
    editRole(item) {
      this.obj = [];
      this.num = 1;
      this.formList = Object.assign({}, item);
      this.dialogVisible = true;
    },
    // 删除角色
    delRole(item) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          if (res == "confirm") {
            removeRole(item.id).then((res) => {
              if (res.success) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.init();
              }
            });
          }
        })
        .catch((res) => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改展示条数
    handleSizeChange(res) {
      this.limit = res;
      this.start = 1;
      this.init();
    },
    // 下一页
    handleCurrentChange(res) {
      this.start = res;
      this.init();
    },
    init() {
      findRolesByPage(this.start, this.limit).then((res) => {
        if (res.success) {
          this.tableList = res.data.rows;
          this.fullData = res.data.total;
        }
      });
    },
    initTreeData() {
      findAllPermissions().then((res) => {
        if (res.success) {
          this.treeData = res.data.menus;
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
  created() {
    this.init();
    this.initTreeData();
  },
};
</script>

<style lang="scss" scoped>
.block {
  margin: 20px auto;
  display: flex;
  justify-content: center;
}
</style>